const fetch = (url, opts = {}, onProgress) =>
    new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(opts.method || 'GET', url);
        Object.keys(opts.headers || {}).forEach(key => {
            xhr.setRequestHeader(key, opts.headers[key]);
        });
        xhr.onload = e => {
            const {
                target: { responseText, status }
            } = e;
            resolve({
                text: () => responseText,
                json: () => JSON.parse(responseText) || {},
                status
            });
        };
        xhr.onerror = reject;
        if (xhr.upload && onProgress) {
            xhr.upload.onprogress = e => {
                const { loaded, total } = e;
                onProgress((loaded / total) * 100);
            };
        }
        xhr.send(opts.body);
    });

// 上传至服务器
const uploadToServer = (url, file, onProgress) => {
    const options = {
        method: 'PUT',
        body: file,
        headers: {
            'Content-Type': 'application/octet-stream'
        }
    };
    const remoteUrl = !url.includes('https') ? url.replace('http', 'https') : url;
    return fetch(remoteUrl, options, progress => {
        onProgress({ percent: progress });
    });
};

const upload = async (file, options) => {
    let result = '';
    const response = await fetch('/api/resource/public/oss/v2/produceputpresignurls', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ richText: '1', fileNames: [file.name] })
    });
    const { data: signResult, code } = response.json();
    if (code === 10000) {
        const { preUrl, url } = signResult[0];
        const { onProgress = () => {} } = options;
        const ossResponse = await uploadToServer(preUrl, file, onProgress);
        const { status } = ossResponse;
        if (status === 200) {
            result = url;
        }
    }
    return result;
};

export default upload;
